<template>
	<view class="container">
		<!-- 作文任务信息卡片 -->
		<view class="task-header">
			<text class="task-title">作文任务</text>
		</view>
		<view class="task-card">
			<view class="task-content">
				<view class="task-info">
					<view class="info-item">
						<text class="info-label">名称:</text>
						<text class="info-value">{{time}} - 作文</text>
					</view>
					<view class="info-item">
						<text class="info-label">时间:</text>
						<text class="info-value">{{time}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">老师:</text>
						<text class="info-value">{{teacherName}}</text>
					</view>
				</view>
				<view class="task-icon">
					<view class="icon-placeholder">
						<image src="/static/home/bgtime.png" class="decoration-img" mode="aspectFit"></image>
					</view>
				</view>
			</view>
		</view>

		<!-- 班级选择 -->
		<view class="section">
			<view class="section-title">班级选择</view>
			<view class="class-selection">
				<view v-for="(item,index) in myClassList" :key="index" :class="{'class-btn-1':setAct==index}"
					class="class-btn" @tap="selectClass(item,index)">
					<image src="/static/home/prop2.png" class="class-icon" mode="aspectFit"></image>
					<text class="class-text">{{item.className}}</text>
				</view>
			</view>
		</view>

		<!-- 默写答案编辑 -->
		<view class="section">
			<view class="section-title">作文要求编辑</view>
			<!-- 拍照上传按钮 -->
			<view class="upload-section f f-a-c f-j-b">
				<view class="upload-btn" @click="select">
					<image src="/static/home/paishe.png" class="upload-icon" mode="aspectFit"></image>
					<text class="upload-text">拍照上传</text>
				</view>

			</view>
			<!-- 上传的图片预览 -->
			<view v-if="uploadedImages.length > 0" class="image-preview-section">
				<view class="preview-title">已上传图片</view>
				<view class="image-list">
					<view v-for="(image, index) in uploadedImages" :key="index" class="image-item">
						<image :src="image.url" class="preview-image" mode="aspectFill" @tap="previewImage(index)">
						</image>
						<view class="delete-btn" @tap="deleteImage(index)">
							<text class="delete-icon">×</text>
						</view>
					</view>
				</view>
			</view>
			<!-- 文本编辑区域 -->
			<view class="text-editor-section">
				<textarea v-model="assignmentContent" class="text-editor" placeholder="默认要求：1. 字迹工整。2. 逻辑合理"
					placeholder-style="color: #999; font-size: 28rpx;" maxlength="500" auto-height @input="onTextInput"
					@focus="onTextFocus" @blur="onTextBlur"></textarea>
				<view class="char-count">
					<text class="count-text">{{ assignmentContent.length }}/500</text>
				</view>
			</view>
		</view>

		<!-- 创建按钮 -->
		<view class="create-section">
			<button class="create-btn" @tap="createTaskZuo">创建作文任务</button>
		</view>

		<view>
			<!-- <button @click="select">选择图片</button> -->
			<ksp-cropper mode="free" :width="200" :height="140" :maxWidth="1024" :maxHeight="1024" :url="url"
				@cancel="oncancel" @ok="onok"></ksp-cropper>
		</view>
		<u-popup mode="center" border-radius="30" v-model="shows">
			<view class="popW">
				<view class="top">
					<view class="tit">
						{{time}}-作文
					</view>
					<view class="botR">
						{{setObj.className}}
					</view>
				</view>
				<view class="boxF">
					<view class="tinD">
						作文要求
					</view>
					<view style="width: 100%;" class="f f-w-w ">
						<textarea v-model="assignmentContent" :disabled="true" class="text-editor"
							placeholder="默认要求：1. 字迹工整。2. 逻辑合理" placeholder-style="color: #999; font-size: 28rpx;"
							maxlength="500" auto-height></textarea>
					</view>
					<view class="btn f f-a-c f-j-c">
						<view @click="shows=false" class="lefbtn f f-a-c f-j-c">
							继续编辑
						</view>
						<view @click="tijiao" class="rig f f-a-c f-j-c">
							好的
						</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				shows: false,
				show: false,
				time: '',
				title: '选择资源',
				url: "",
				teacherName: uni.getStorageSync('teacherName'),
				// path: "",
				myClassList: [],
				taskInfo: {
					name: '2025.5.20-听写1',
					date: '2025.5.20',
					teacher: '小明'
				},
				selectedClass: '',
				setAct: -1,
				setObj: {},
				assignmentContent: '1. 字迹工整\n2. 逻辑合理',
				uploadedImages: [],
				isTextFocused: false
			}
		},

		computed: {
			canCreate() {
				return this.selectedClass && (this.assignmentContent.trim() || this.uploadedImages.length > 0);
			}
		},
		onShow() {
			this.init()
		},
		onLoad() {
			this.time = uni.$u.timeFormat(this.timestamp, 'mm-dd hh:MM:ss');
		},
		methods: {
			// 获取班级信息
			async init() {
				let teacher = await this.$api.classList({
					teacherId: uni.getStorageSync('teacherId')
				})
				if (teacher && teacher.data) {
					this.myClassList = teacher.data
				}
			},
			// 点击提交任务
			async tijiao() {

				let n = await this.$api.createZuowen({
					"taskTitle": `${this.time}-作文`, //标题，唯一标识
					"taskType": "composition", //composition作文、dictate听写、dictation默写
					"teacherId": uni.getStorageSync('teacherId'), //老师的id
					"classId": this.setObj.classId, //选择的班级
					"taskContent": JSON.stringify(this.assignmentContent.split('\n').filter(item => item
						.trim() !== '')), //识别内容
					"schoolId": uni.getStorageSync('schoolId')
				})
				if (n.code == '0000') {
					this.$msg('创建成功')
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}, 1000)
				}
			},
			tihuan(item) {
				this.show = false
			},
			// 作文任务
			createTaskZuo() {
				if (this.setAct == -1) {
					this.$msg('请选择班级')
					return
				}
				if (this.assignmentContent.length == 0) {
					return this.$msg('请上传要求')
				}
				this.shows = true
			},
			select() {
				uni.showActionSheet({
					itemList: ['拍照', '从相册选择'],
					success: (res) => {
						const sourceType = res.tapIndex === 0 ? ['camera'] : ['album'];
						uni.chooseImage({
							count: 1,
							success: (rst) => {
								// 设置url的值，显示控件
								this.url = rst.tempFilePaths[0];
								// this.uploadedImages.push({
								// 	url: rst.tempFilePaths[0],
								// 	name: `image_${Date.now()}.jpg`
								// })
							}
						});

					}
				});

			},
			onok(ev) {
				this.url = "";
				// this.path = ev.path;
				this.uploadedImages.push({
					url: ev.path,
					name: `image_${Date.now()}.jpg`
				})
			},
			oncancel() {
				// url设置为空，隐藏控件
				this.url = "";
			},
			// 选择班级
			selectClass(item, index) {

				this.setAct = index
				this.setObj = item

			},

			// 拍照上传 - 添加裁剪功能
			uploadPhoto() {
				uni.showActionSheet({
					itemList: ['拍照', '从相册选择'],
					success: (res) => {
						const sourceType = res.tapIndex === 0 ? ['camera'] : ['album'];

						uni.chooseImage({
							count: 1, // 一次只选择一张进行裁剪
							sizeType: ['original', 'compressed'],
							sourceType: sourceType,
							success: (res) => {
								const tempFilePath = res.tempFilePaths[0];
								// 调用裁剪功能
								// this.cropImage(tempFilePath);
							},
							fail: (err) => {
								console.error('选择图片失败:', err);
								uni.showToast({
									title: '选择图片失败',
									icon: 'none'
								});
							}
						});
					}
				});
			},

			// 图片裁剪功能
			// 预览图片
			previewImage(index) {
				const urls = this.uploadedImages.map(img => img.url);
				uni.previewImage({
					urls: urls,
					current: index
				});
			},

			// 删除图片
			deleteImage(index) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这张图片吗？',
					success: (res) => {
						if (res.confirm) {
							this.uploadedImages.splice(index, 1);
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						}
					}
				});
			},

			// 文本输入事件
			onTextInput(e) {
				this.assignmentContent = e.detail.value;
			},

			// 文本框获得焦点
			onTextFocus() {
				this.isTextFocused = true;
			},

			// 文本框失去焦点
			onTextBlur() {
				this.isTextFocused = false;
			},

			// 创建作文任务
			createAssignment() {
				if (!this.canCreate) {
					uni.showToast({
						title: '请完善任务信息',
						icon: 'none'
					});
					return;
				}

				// 构建任务数据
				const assignmentData = {
					name: this.taskInfo.name,
					date: this.taskInfo.date,
					teacher: this.taskInfo.teacher,
					class: this.selectedClass,
					content: this.assignmentContent,
					images: this.uploadedImages,
					createTime: new Date().toISOString()
				};

				uni.showLoading({
					title: '创建中...'
				});

				// 模拟API调用
				setTimeout(() => {
					uni.hideLoading();

					uni.showModal({
						title: '创建成功',
						content: `作文任务已成功创建并发布给${this.selectedClass}`,
						showCancel: false,
						success: () => {
							// 返回上一页或跳转到任务列表
							uni.navigateBack({
								delta: 1
							});
						}
					});
				}, 2000);
			},

			// 保存草稿
			saveDraft() {
				const draftData = {
					selectedClass: this.selectedClass,
					assignmentContent: this.assignmentContent,
					uploadedImages: this.uploadedImages,
					saveTime: new Date().toISOString()
				};

				uni.setStorageSync('assignment_draft', draftData);
				uni.showToast({
					title: '草稿已保存',
					icon: 'success'
				});
			},

			// 加载草稿
			loadDraft() {
				try {
					const draftData = uni.getStorageSync('assignment_draft');
					if (draftData) {
						this.selectedClass = draftData.selectedClass || '';
						this.assignmentContent = draftData.assignmentContent || '';
						this.uploadedImages = draftData.uploadedImages || [];
					}
				} catch (e) {
					console.error('加载草稿失败:', e);
				}
			}
		},

	}
</script>

<style lang="scss" scoped>
	.popW {
		width: 700rpx;

		.top {
			width: 100%;
			height: 104rpx;
			background: #C8FFE2;
			padding: 10rpx 30rpx;

			.tit {
				font-family: SourceHanSansCN, SourceHanSansCN;
				font-weight: bold;
				text-align: center;
				font-size: 36rpx;
				color: #000000;
			}

			.botR {
				font-family: SourceHanSansCN, SourceHanSansCN;
				font-weight: 400;
				font-size: 24rpx;
				text-align: right;
				color: #333333;
			}
		}

		.boxF {
			background-color: #fff;
			padding: 30rpx;

			.btn {
				margin-top: 60rpx;

				.lefbtn {
					width: 212rpx;
					height: 68rpx;
					background: #CCCCCC;
					border-radius: 45rpx;
					font-weight: 500;
					font-size: 28rpx;
					color: #FFFFFF;
				}

				.rig {
					font-weight: 500;
					font-size: 28rpx;
					color: #FFFFFF;
					width: 208rpx;
					height: 68rpx;
					margin-left: 50rpx;
					background: #05C490;
					border-radius: 45rpx;
				}
			}

			.tinD {
				font-family: SourceHanSansCN, SourceHanSansCN;
				font-weight: 500;
				font-size: 32rpx;
				margin-bottom: 30rpx;
				color: #000000;
			}

			.fcen {
				width: 22%;

				font-family: SourceHanSansCN, SourceHanSansCN;
				font-weight: 500;
				font-size: 28rpx;
				padding: 10rpx 40rpx;
				border-radius: 44rpx;
				background-color: #FDE5E5;
				color: #333333;
				margin-right: 4%;
				margin-bottom: 20rpx;

				&:nth-child(4n) {
					margin-right: 0;
				}
			}
		}
	}


	.rigBox {
		.rig {
			position: relative;
			padding: 0 10rpx;
			width: 174rpx;
			height: 56rpx;
			border-radius: 10rpx;
			border: 2rpx solid #979797;
			font-family: SourceHanSansCN, SourceHanSansCN;
			font-weight: 400;
			font-size: 24rpx;
			color: #999999;

			.box {
				border: 2rpx solid #666;
				position: absolute;
				height: 300rpx;
				width: 100%;
				font-family: SourceHanSansCN, SourceHanSansCN;
				font-weight: 400;
				font-size: 24rpx;
				color: #999999;
				bottom: -300rpx;
				z-index: 9999999;
				left: 0;
				overflow: auto;
				background-color: #fff;

				.boxZi {
					height: 55rpx;
				}
			}

			.box::-webkit-scrollbar {
				width: 0;
				/* 滚动条宽度 */
			}

			.xiala {
				width: 17rpx;
				height: 17rpx;
			}
		}
	}

	.container {
		height: 100vh;
		background-color: #fff;
		padding: 30rpx;
		padding-bottom: 120rpx; // 为底部按钮留出空间
	}

	.task-card {
		background: linear-gradient(135deg, #a8e6cf 0%, #88d8a3 100%);
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		position: relative;
		overflow: hidden;
	}

	.task-header {
		margin-bottom: 20rpx;
	}

	.task-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #2c3e50;
	}

	.task-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.task-info {
		flex: 1;
	}

	.info-item {
		display: flex;
		margin-bottom: 10rpx;
	}

	.info-label {
		font-size: 28rpx;
		color: #34495e;
		margin-right: 10rpx;
	}

	.info-value {
		font-size: 28rpx;
		color: #2c3e50;
		font-weight: 500;
	}

	.task-icon {
		width: 120rpx;
		height: 120rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.icon-placeholder {
		width: 130rpx;
		height: 208rpx;
	}

	.decoration-img {
		width: 130rpx;
		height: 208rpx;
	}

	.section {
		margin-bottom: 40rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #2c3e50;
		margin-bottom: 20rpx;
	}


	.class-selection {
		display: flex;
		flex-wrap: wrap;
		// gap: 20rpx;
	}

	.class-btn {
		width: 48%;
		margin-right: 2%;
		height: 120rpx;
		margin-bottom: 20rpx;
		border-radius: 20rpx;
		display: flex;
		font-size: 28rpx;
		font-weight: 500;
		align-items: center;
		justify-content: center;
		position: relative;
		overflow: hidden;
		border: 2rpx solid #ccc;
		color: #000;

		&:nth-child(2n) {
			margin-right: 0;
		}
	}

	.class-btn-1 {
		background: #64D2FD;
		color: #fff;
	}

	.class-btn-2 {
		// background: #64D2FD;
	}

	.class-icon {
		width: 74rpx;
		height: 68rpx;
		margin-right: 30rpx;
	}


	.upload-section {
		margin-bottom: 30rpx;
	}

	.upload-btn {
		width: 296rpx;
		height: 104rpx;
		border-radius: 30rpx;
		border: 4rpx solid #6F7E9F;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;

		&:active {
			background-color: #f8f9fa;
			border-color: #007bff;
		}
	}

	.upload-icon {
		width: 52rpx;
		height: 48rpx;
		margin-right: 34rpx;
	}

	.upload-text {
		font-size: 32rpx;
		color: #4A5C85;
	}

	.text-editor-section {
		background-color: white;
		border-radius: 10rpx;
		border: 2rpx solid #979797;
		padding: 20rpx;
		position: relative;
	}

	.text-editor {
		width: 100%;
		min-height: 300rpx;
		font-size: 28rpx;
		line-height: 1.6;
		color: #333;
		background-color: transparent;

	}

	.char-count {
		position: absolute;
		bottom: 10rpx;
		right: 15rpx;
	}

	.count-text {
		font-size: 24rpx;
		color: #999;
	}

	.create-section {
		position: fixed;
		bottom: 20rpx;
		width: 90%;
		margin-top: 60rpx;
		padding-bottom: 40rpx;
	}

	.create-btn {
		width: 100%;
		height: 88rpx;
		background: #05C490;
		color: white;
		border: none;
		border-radius: 44rpx;
		font-family: SourceHanSansCN, SourceHanSansCN;
		font-weight: 500;
		font-size: 36rpx;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
	}


	.create-btn::after {
		border: none;
	}

	.image-preview-section {
		background-color: white;
		border-radius: 15rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
	}

	.preview-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 20rpx;
	}

	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}

	.image-item {
		position: relative;
		width: 150rpx;
		height: 150rpx;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.preview-image {
		width: 100%;
		height: 100%;
	}

	.delete-btn {
		position: absolute;
		top: -5rpx;
		right: -5rpx;
		width: 40rpx;
		height: 40rpx;
		background-color: #ff4757;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.delete-icon {
		color: white;
		font-size: 24rpx;
		font-weight: bold;
	}
</style>